package com.smartao.core.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class ConnectionManager {

	protected final Logger logger = LoggerFactory.getLogger(ConnectionManager.class);
	
	@Value("#{applicationProperties['jdbc.driver']}")
	private String jdbcDriver;
	
	@Value("#{applicationProperties['jdbc.url']}")
	private String url;
	
	@Value("#{applicationProperties['jdbc.username']}")
	private String username;
	
	@Value("#{applicationProperties['jdbc.password']}")
	private String password;
	
	@PostConstruct
	public void init() {
		try {
			Class.forName(jdbcDriver);
		} catch (ClassNotFoundException e) {
			logger.error("Can't found jdbc driver" + jdbcDriver, e);
		}
	}
	public void init(Properties props) {
		this.jdbcDriver = props.getProperty("jdbc.driver");
		this.url = props.getProperty("jdbc.url");
		this.username = props.getProperty("jdbc.username");
		this.password = props.getProperty("jdbc.password");
		
		try {
			Class.forName(jdbcDriver);
		} catch (ClassNotFoundException e) {
			logger.error("Can't found jdbc driver" + jdbcDriver, e);
		}
	}

	public Connection getConnection() {
		return getConnection(url,username,password);
	}
	
	public Connection getConnection(String url, String username, String password) {
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			logger.error("Can't get connection ", e);
		}
		return conn;
	}


	public void closeConnection(Connection conn) {
		try {
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			logger.error("Can't close connection ", e);
		}
	}
}
